package com.github.controller;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.github.bean.ServerUser;
import com.github.bean.ServerUserSession;
import com.github.common.constant.MyConstant;
import com.github.manager.Manager;
import com.github.service.UserServer;
import com.github.util.Role;
import com.github.util.SessionSocketHolder;
import com.github.util.SocketSendThread;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;

@RestController
public class ManagerController {
    private ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    private ServerProperties serverProperties;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserServer userServer;

    @GetMapping("/api/manager/getManger")
    public ObjectNode getManger(String type) {
        try {
            ObjectNode jsonObject = objectMapper.createObjectNode();
            ObjectNode detailsNode = objectMapper.createObjectNode();
            List<ServerUserSession> allUserSession = SessionSocketHolder.getAllUserSession();
            List<String> allAccount = SessionSocketHolder.getAllAccount();
            // 根据不同type返回详细信息
            switch (type) {
                case "accountUserMap":
                    // 返回所有ws账户的详细信息
                    jsonObject.put("总数", allUserSession.size());
                    jsonObject.put("server在线数", allUserSession.stream()
                            .filter(item->item.getDeviceType().equals(Role.SERVER))
                            .count());
                    jsonObject.put("voice在线数", allUserSession.stream()
                            .filter(item -> item.getDeviceType().equals(Role.VOICE))
                            .count());
                    jsonObject.put("card在线数", allUserSession.stream()
                            .filter(item -> item.getDeviceType().equals(Role.CALL))
                            .count());
                    for (String account : allAccount) {

                        ObjectNode userJson = objectMapper.createObjectNode();
                        userJson.put("account", account);
                        userJson.put("serverSession", SessionSocketHolder.isOpen(SessionSocketHolder.get(account,Role.SERVER)));
                        userJson.put("voiceSession", SessionSocketHolder.isOpen(SessionSocketHolder.get(account,Role.VOICE)));
                        userJson.put("cardSession",  SessionSocketHolder.isOpen(SessionSocketHolder.get(account,Role.CALL)));
                        detailsNode.set(account, userJson);
                    }
                    jsonObject.set("详情", detailsNode);
                    break;
                case "sessionIDUserMap":
                    // 返回所有ws连接的详细信息
                    jsonObject.put("总数", allUserSession.size());
                    for (ServerUserSession serverUserSession : allUserSession) {


                        ObjectNode userJson = objectMapper.createObjectNode();
                        userJson.put("account", serverUserSession.getAccount());
//                    userJson.put("serverSessionId", serverUser.getServerSessionId());
//                    userJson.put("voiceSessionId", serverUser.getVoiceSessionId());
//                    userJson.put("cardSessionId", serverUser.getCardSessionId());
                        detailsNode.set(serverUserSession.getSession().getId(), userJson);
                    }
                    jsonObject.set("详情", detailsNode);
                    break;
//            case "connectionCount":
//                // 连接计数是累计值，返回当前值和说明
//                jsonObject.put("当前连接计数值", Manager.connectionCount.get());
//                break;
                case "sessionQueues":
                    // 返回消息队列的详细信息
                    jsonObject.put("总数", SocketSendThread.sessionQueues.size());
                    for (Map.Entry<String, BlockingQueue<String>> entry : SocketSendThread.sessionQueues.entrySet()) {
                        String key = entry.getKey();
                        BlockingQueue<String> queue = entry.getValue();
                        detailsNode.put(key, queue.size());
                    }
                    jsonObject.set("详情", detailsNode);
                    break;
                default:
                    // 处理未知类型
                    jsonObject.put("ws账户类型数", allUserSession.size() + "-" + SessionSocketHolder.serverUserSessionMap.size());
                    jsonObject.put("seesion数", SessionSocketHolder.serverUserAccountMap.size());

                    jsonObject.put("ws消息队列数", SocketSendThread.sessionQueues.size());
                    jsonObject.put("redis账户数", stringRedisTemplate.opsForHash().entries(MyConstant.UserInfoCache).size());
                    jsonObject.put("数据库账户数", userServer.getAllUser().size());
                    jsonObject.put("UserLoginToken-token-account", stringRedisTemplate.opsForHash().entries(MyConstant.UserLoginToken).size());
                    jsonObject.put("UserLoginAccount-account-token", stringRedisTemplate.opsForHash().entries(MyConstant.UserLoginAccount).size());
                    // 获取当前活跃线程数
                    int activeThreads = Thread.activeCount();
                    jsonObject.put("获取当前活跃线程数", activeThreads);

                    // 获取所有线程的详细信息
                    ThreadGroup group = Thread.currentThread().getThreadGroup();
                    ThreadGroup topGroup = group;
                    // 遍历获取最顶层的线程组
                    while (group != null) {
                        topGroup = group;
                        group = group.getParent();
                    }
                    // 估算线程数量
                    int estimatedSize = topGroup.activeCount() * 2;
                    Thread[] threads = new Thread[estimatedSize];
                    // 获取所有线程
                    int actualSize = topGroup.enumerate(threads);
                    jsonObject.put("获取所有线程", actualSize);

                    // 获取配置的线程池参数
                    int maxThreads = serverProperties.getTomcat().getThreads().getMax();
                    int minSpareThreads = serverProperties.getTomcat().getThreads().getMinSpare();

                    jsonObject.put("Tomcat最大线程数", maxThreads);
                    jsonObject.put("Tomcat最小空闲线程数", minSpareThreads);
                    break;
            }
            return objectMapper.createObjectNode().set("message", jsonObject);
        } catch (Exception e) {
            return objectMapper.createObjectNode().put("message", e.getMessage());
        }
    }
}
